package com.ktjy.controller;


import com.alibaba.fastjson.JSONObject;
import com.ktjy.pojo.SysRole;
import com.ktjy.pojo.SysUser;
import com.ktjy.service.SysRoleService;
import com.ktjy.service.SysUserService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import util.Constants;
import util.PageSupport;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/user")
public class SysUserController {
    private Logger logger=Logger.getLogger(SysUserController.class);

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    //跳转到登录页面
    @RequestMapping("/tologin")
    public String login(){
        return "login";
    }

    //登录
    @RequestMapping("/login")
    public String doLogin(@RequestParam(value = "realName")String realName,
                          @RequestParam(value = "password")String password,
                          HttpSession session, HttpServletRequest request){
        logger.debug("登陆方法");
        //调用Service方法,进行用户匹配
        SysUser sysUser=sysUserService.login(realName,password);
        if(null != sysUser){
            //将用户信息放入session
            session.setAttribute(Constants.USER_SESSION,sysUser);
            //登录成功，重定向到/user/toMain接口
            return "redirect:/user/toMain";
        }else {
            request.setAttribute("error","账号或密码不正确");
            //用户不存在，跳转到登录页面
            return "login";
        }
    }

    //跳转到主页面
    @RequestMapping("/toMain")
    public String main(){
        return "frame";
    }

    @GetMapping("/list")
    public String getUserList(Model model,String queryRealName,Integer queryRoleId,
                              @RequestParam(defaultValue = "1")Integer pageIndex){
        List<SysUser> usersList=null;
        try{
            //设置页面容量
            int pageSize=Constants.pageSize;
            //总数量
            int totalCount=sysUserService.getUserCount(queryRealName,queryRoleId);
            //总页数
            PageSupport pages = new PageSupport();
            pages.setCurrentPageNo(pageIndex);
            pages.setPageSize(pageSize);
            pages.setTotalPageCount(totalCount);
            int totalPageCount=pages.getTotalPageCount();
            //控制首页和尾页
            if(pageIndex>totalPageCount){
                pageIndex=totalPageCount;
                throw new RuntimeException("页码不正确");
            }
            usersList=sysUserService.getUserList(queryRealName,queryRoleId,pageSize,pageIndex);
            System.out.println(usersList);
            model.addAttribute("userList",usersList);
            List<SysRole> roleList=sysRoleService.getRoleList();
            model.addAttribute("roleList",roleList);
            model.addAttribute("queryRealName",queryRealName);
            model.addAttribute("queryRoleId",queryRoleId);
            model.addAttribute("totalPageCount",totalPageCount);
            model.addAttribute("totalCount",totalCount);
            model.addAttribute("currentPageNo",pageIndex);
        }catch (Exception e){
            e.printStackTrace();
            logger.error("获取用户列表失败");
        }
        return "sysUser/list";
    }

    /**
     * 跳转新增页面
     * @return
     */
    @GetMapping("/toAdd")

    public String toAdd(){
        return "sysUser/add";
    }

    //新增
    @PostMapping("/add")
    public String add(SysUser sysUser,HttpSession session){
        SysUser create= (SysUser) session.getAttribute(Constants.USER_SESSION);
        sysUser.setCreadUserId(create.getId());
        if(sysUserService.add(sysUser)){
            return "redirect:/user/list";
        }else {
            return "sysUser/add";
        }
    }

    //同名验证
    @GetMapping("userExist")
    @ResponseBody
    public String userExist(String account){
        JSONObject jsonObject=new JSONObject();
        try{
          int exist=sysUserService.getUserExist(account,null);
          jsonObject.put("exist",exist);
        }catch (Exception e){
         jsonObject.put("exist",-1);
         jsonObject.put("message",e);
        }
        return jsonObject.toJSONString();
    }

    //查询用户详情
    @GetMapping("/view/{id}")
    public String userview(@PathVariable Integer id,Model model){
        logger.debug("根据id查询用户详情"+id);
        SysUser sysUser=sysUserService.getUserById(Math.toIntExact(id));
        model.addAttribute(sysUser);
        return "sysUser/view";
    }

    /**
     * 删除方法
     * @param id
     * @return
     */
    @DeleteMapping("/del/{id}")
    @ResponseBody
    public String delete(@PathVariable Integer id) {
        JSONObject jsonObject = new JSONObject();
        try{
            Boolean success = sysUserService.removeById(id); // 假设delete方法返回一个boolean表示是否成功
            System.out.println(success.toString()+"删除");
            jsonObject.put("delResult",success.toString());
        }catch(Exception e){
            jsonObject.put("delResult","notexist");
            e.printStackTrace();
        }
        return jsonObject.toJSONString();
      }

    /**
      * 根据id修改
     * @param id
     * @return
     */

      @GetMapping("/toUpdate/{id}")
      public String update(@PathVariable Integer id){
        SysUser sysUser=sysUserService.getUserById(id);
        if(sysUser != null){
            return "sysUser/update";
        }
        return "sysError";
      }
}
